-- socket流处理

local socket = require "client.socket"
local crypt = require "client.crypt"

local _M = {} 

local last = ""

local function unpack_package(text)
	local size = #text
	if size < 2 then
		return nil, text
	end
	local s = text:byte(1) * 256 + text:byte(2)
	if size < s+2 then
		return nil, text
	end

	return text:sub(3,2+s), text:sub(3+s)
end

local function recv_package(fd, last)
	local result
	result, last = unpack_package(last)
	if result then
		return result, last
	end
	local r = socket.recv(fd)
	if not r then
		return nil, last
	end
	if r == "" then
		error "Server closed"
	end
	return unpack_package(last .. r)
end

function _M.read_package(fd)
    while true do 
        local result 
        result, last = recv_package(fd, last) 

        if result then 
            return result 
        end 

        socket.usleep(100)
    end 
end 

function _M.try_read_package(fd) 
    local result 
    result, last = recv_package(fd, last) 
    if result then 
        return result
    end 
end 

function _M.connect(addr, port)
    local fd = assert(socket.connect(addr, port), "[socket connect failed]")
    return fd
end

function _M.close(fd)
    if fd ~= nil then 
    	socket.close(fd)
		fd = nil 
	end
end

function _M.send_package(fd, pack)
	local package = string.pack(">s2", pack)
	socket.send(fd, package)
end

return _M 